package 字符串;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 帅小伙
 * @date 2021/12/23
 * @description   最长不含重复字符的子字符串
 */
public class Demo06 {


    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("df"));
    }


/*
*   int[] dp = new int[s.length() + 1];
        // HashMap存储字符出现的位置，char - idx
        Map<Character, Integer> map = new HashMap();
        int maxLen = 0;
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (!map.containsKey(ch)) {
                dp[i + 1] = dp[i] + 1;
            } else { // abaa
                dp[i + 1] = Math.min(i - map.get(ch), dp[i] + 1);
            }
            map.put(ch, i);
            maxLen = Math.max(maxLen, dp[i + 1]);
        }

        return maxLen;
* */

    public static int lengthOfLongestSubstring (String s) {
        int[] dp = new int[s.length() + 1];
        // HashMap存储字符出现的位置，char - idx
        Map<Character, Integer> map = new HashMap();
        int maxLen = 0;
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (!map.containsKey(ch)) {
                dp[i + 1] = dp[i] + 1;
            } else {
                dp[i + 1] = Math.min(i - map.get(ch), dp[i] + 1);
            }
            map.put(ch, i);
            maxLen = Math.max(maxLen, dp[i + 1]);
        }

        return maxLen;
    }
}
